<!DOCTYPE HTML>
<html lang="zh-CN">




<head>
    <meta charset="utf-8">
    <meta name="keywords" content="&#39;JavaNote06_IOStream&#39;, 深度学习 故障诊断 Java">
    <meta name="description" content="河海大学 | 计算机与信息学院 | 信号与信息处理">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
    <meta name="renderer" content="webkit|ie-stand|ie-comp">
    <meta name="mobile-web-app-capable" content="yes">
    <meta name="format-detection" content="telephone=no">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
    <!-- Global site tag (gtag.js) - Google Analytics -->


    <title>&#39;JavaNote06_IOStream&#39; | 世庆的博客</title>
    <link rel="icon" type="image/png" href="/shiqing/favicon.png">

    <link rel="stylesheet" type="text/css" href="/shiqing/libs/awesome/css/all.css">
    <link rel="stylesheet" type="text/css" href="/shiqing/libs/materialize/materialize.min.css">
    <link rel="stylesheet" type="text/css" href="/shiqing/libs/aos/aos.css">
    <link rel="stylesheet" type="text/css" href="/shiqing/libs/animate/animate.min.css">
    <link rel="stylesheet" type="text/css" href="/shiqing/libs/lightGallery/css/lightgallery.min.css">
    <link rel="stylesheet" type="text/css" href="/shiqing/css/matery.css">
    <link rel="stylesheet" type="text/css" href="/shiqing/css/my.css">

    <script src="/shiqing/libs/jquery/jquery.min.js"></script>

    <script src="https://sdk.jinrishici.com/v2/browser/jinrishici.js" charset="utf-8"></script>
<meta name="generator" content="Hexo 6.3.0"></head>




    <body>
        <header class="navbar-fixed">
    <nav id="headNav" class="bg-color nav-transparent">
        <div id="navContainer" class="nav-wrapper container">
            <div class="brand-logo">
                <a href="/shiqing/" class="waves-effect waves-light">
                    
                    <img src="/shiqing/medias/logo.png" class="logo-img" alt="LOGO">
                    
                    <span class="logo-span">世庆的博客</span>
                </a>
            </div>
            

<a href="#" data-target="mobile-nav" class="sidenav-trigger button-collapse"><i class="fas fa-bars"></i></a>
<ul class="right nav-menu">
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/shiqing/" class="waves-effect waves-light">
      
      <i class="fas fa-home" style="zoom: 0.6;"></i>
      
      <span>首页</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/shiqing/tags" class="waves-effect waves-light">
      
      <i class="fas fa-tags" style="zoom: 0.6;"></i>
      
      <span>标签</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/shiqing/categories" class="waves-effect waves-light">
      
      <i class="fas fa-bookmark" style="zoom: 0.6;"></i>
      
      <span>分类</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/shiqing/archives" class="waves-effect waves-light">
      
      <i class="fas fa-archive" style="zoom: 0.6;"></i>
      
      <span>归档</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/shiqing/about" class="waves-effect waves-light">
      
      <i class="fas fa-user-circle" style="zoom: 0.6;"></i>
      
      <span>关于</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/shiqing/contact" class="waves-effect waves-light">
      
      <i class="fas fa-comments" style="zoom: 0.6;"></i>
      
      <span>留言板</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/shiqing/friends" class="waves-effect waves-light">
      
      <i class="fas fa-address-book" style="zoom: 0.6;"></i>
      
      <span>友情链接</span>
    </a>
    
  </li>
  
  <li>
    <a href="#searchModal" class="modal-trigger waves-effect waves-light">
      <i id="searchIcon" class="fas fa-search" title="搜索" style="zoom: 0.85;"></i>
    </a>
  </li>
</ul>


<div id="mobile-nav" class="side-nav sidenav">

    <div class="mobile-head bg-color">
        
        <img src="/shiqing/medias/logo.png" class="logo-img circle responsive-img">
        
        <div class="logo-name">世庆的博客</div>
        <div class="logo-desc">
            
            河海大学 | 计算机与信息学院 | 信号与信息处理
            
        </div>
    </div>

    

    <ul class="menu-list mobile-menu-list">
        
        <li class="m-nav-item">
	  
		<a href="/shiqing/" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-home"></i>
			
			首页
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/shiqing/tags" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-tags"></i>
			
			标签
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/shiqing/categories" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-bookmark"></i>
			
			分类
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/shiqing/archives" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-archive"></i>
			
			归档
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/shiqing/about" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-user-circle"></i>
			
			关于
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/shiqing/contact" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-comments"></i>
			
			留言板
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/shiqing/friends" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-address-book"></i>
			
			友情链接
		</a>
          
        </li>
        
        
        <li><div class="divider"></div></li>
        <li>
            <a href="https://github.com/sqtian-hhu/" class="waves-effect waves-light" target="_blank">
                <i class="fab fa-github-square fa-fw"></i>Fork Me
            </a>
        </li>
        
    </ul>
</div>


        </div>

        
            <style>
    .nav-transparent .github-corner {
        display: none !important;
    }

    .github-corner {
        position: absolute;
        z-index: 10;
        top: 0;
        right: 0;
        border: 0;
        transform: scale(1.1);
    }

    .github-corner svg {
        color: #0f9d58;
        fill: #fff;
        height: 64px;
        width: 64px;
    }

    .github-corner:hover .octo-arm {
        animation: a 0.56s ease-in-out;
    }

    .github-corner .octo-arm {
        animation: none;
    }

    @keyframes a {
        0%,
        to {
            transform: rotate(0);
        }
        20%,
        60% {
            transform: rotate(-25deg);
        }
        40%,
        80% {
            transform: rotate(10deg);
        }
    }
</style>

<a href="https://github.com/sqtian-hhu/" class="github-corner tooltipped hide-on-med-and-down" target="_blank"
   data-tooltip="Fork Me" data-position="left" data-delay="50">
    <svg viewBox="0 0 250 250" aria-hidden="true">
        <path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"></path>
        <path d="M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2"
              fill="currentColor" style="transform-origin: 130px 106px;" class="octo-arm"></path>
        <path d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z"
              fill="currentColor" class="octo-body"></path>
    </svg>
</a>
        
    </nav>

</header>

        



<div class="bg-cover pd-header post-cover" style="background-image: url('/shiqing/medias/featureimages/21.jpg')">
    <div class="container" style="right: 0px;left: 0px;">
        <div class="row">
            <div class="col s12 m12 l12">
                <div class="brand">
                    <h1 class="description center-align post-title">&#39;JavaNote06_IOStream&#39;</h1>
                </div>
            </div>
        </div>
    </div>
</div>




<main class="post-container content">

    
    <link rel="stylesheet" href="/shiqing/libs/tocbot/tocbot.css">
<style>
    #articleContent h1::before,
    #articleContent h2::before,
    #articleContent h3::before,
    #articleContent h4::before,
    #articleContent h5::before,
    #articleContent h6::before {
        display: block;
        content: " ";
        height: 100px;
        margin-top: -100px;
        visibility: hidden;
    }

    #articleContent :focus {
        outline: none;
    }

    .toc-fixed {
        position: fixed;
        top: 64px;
    }

    .toc-widget {
        width: 345px;
        padding-left: 20px;
    }

    .toc-widget .toc-title {
        padding: 35px 0 15px 17px;
        font-size: 1.5rem;
        font-weight: bold;
        line-height: 1.5rem;
    }

    .toc-widget ol {
        padding: 0;
        list-style: none;
    }

    #toc-content {
        padding-bottom: 30px;
        overflow: auto;
    }

    #toc-content ol {
        padding-left: 10px;
    }

    #toc-content ol li {
        padding-left: 10px;
    }

    #toc-content .toc-link:hover {
        color: #42b983;
        font-weight: 700;
        text-decoration: underline;
    }

    #toc-content .toc-link::before {
        background-color: transparent;
        max-height: 25px;

        position: absolute;
        right: 23.5vw;
        display: block;
    }

    #toc-content .is-active-link {
        color: #42b983;
    }

    #floating-toc-btn {
        position: fixed;
        right: 15px;
        bottom: 76px;
        padding-top: 15px;
        margin-bottom: 0;
        z-index: 998;
    }

    #floating-toc-btn .btn-floating {
        width: 48px;
        height: 48px;
    }

    #floating-toc-btn .btn-floating i {
        line-height: 48px;
        font-size: 1.4rem;
    }
</style>
<div class="row">
    <div id="main-content" class="col s12 m12 l9">
        <!-- 文章内容详情 -->
<div id="artDetail">
    <div class="card">
        <div class="card-content article-info">
            <div class="row tag-cate">
                <div class="col s7">
                    
                    <div class="article-tag">
                        
                            <a href="/shiqing/tags/Java%E5%9F%BA%E7%A1%80/">
                                <span class="chip bg-color">Java基础</span>
                            </a>
                        
                    </div>
                    
                </div>
                <div class="col s5 right-align">
                    
                    <div class="post-cate">
                        <i class="fas fa-bookmark fa-fw icon-category"></i>
                        
                            <a href="/shiqing/categories/Java/" class="post-category">
                                Java
                            </a>
                        
                    </div>
                    
                </div>
            </div>

            <div class="post-info">
                
                <div class="post-date info-break-policy">
                    <i class="far fa-calendar-minus fa-fw"></i>发布日期:&nbsp;&nbsp;
                    2020-03-26
                </div>
                

                

                

                

                
            </div>
        </div>
        <hr class="clearfix">

        
        <!-- 是否加载使用自带的 prismjs. -->
        <link rel="stylesheet" href="/shiqing/libs/prism/prism.css">
        

        

        <div class="card-content article-card-content">
            <div id="articleContent">
                <h2 id="IO概述"><a href="#IO概述" class="headerlink" title="IO概述"></a>IO概述</h2><p>I：input<br>O：output<br>流：数据，一个字符&#x3D;2个字节&#x3D;16个二进制位<br>java.io<br>字节流：一切文件数据存储时都是以二进制数字的形式保存的</p>
<p>字节输出流:java.io.OutputStream,此抽象类是表示输出字节流的所有类的超类<br>定义了一些子类共性的成员方法:<br>void close()<br>关闭此输出流并释放与此流相关联的任何系统资源。<br>void flush()<br>刷新此输出流并强制任何缓冲的输出字节被写出。<br>void write(byte[] b)<br>将 b.length字节从指定的字节数组写入此输出流。<br>void write(byte[] b, int off, int len)<br>从指定的字节数组写入len个字节，从偏移off开始输出到此输出流。<br>abstract void write(int b)<br>将指定的字节写入此输出流。 </p>
<span id="more"></span>

<p>java.io.FileOutputStream extends OutputStream</p>
<p>文件字节输出流,把内存中的数据写入到硬盘的文件中<br>构造方法:<br>FileOutputStream(String name)<br>创建文件输出流以指定的名称写入文件。<br>FileOutputStream(File file)<br>创建文件输出流以写入由指定的 File对象表示的文件。<br>构造方法的作用:</p>
<ol>
<li>创建一个FileOutputStream对象</li>
<li>会根据构造方法中传递的文件&#x2F;文件路径,创建一个空的文件</li>
<li>会把FileOutputStream对象指向创建好的文件</li>
</ol>
<p>写入数据的原理(内存-&gt;硬盘)<br>    java程序-&gt;JVM-&gt;OS(操作系统)-&gt;OS调用写数据方法-&gt;把数据写入到文件中</p>
<p>字节输出流的使用步骤(重点)</p>
<ol>
<li>创建一个FileOutputStream对象,构造方法中传递写入数据的目的地</li>
<li>调用FileOutputStream对象中的方法write,把数据写入文件中</li>
<li>释放资源(流使用会占用一定的内存,使用完清空)</li>
</ol>
<h2 id="public-class-Demo01OutputStream-public-static-void-main-String-args-try-FileOutputStream-fos-x3D-new-FileOutputStream-“F-a-txt”-fos-write-97-fos-close-catch-IOException-e-e-printStackTrace"><a href="#public-class-Demo01OutputStream-public-static-void-main-String-args-try-FileOutputStream-fos-x3D-new-FileOutputStream-“F-a-txt”-fos-write-97-fos-close-catch-IOException-e-e-printStackTrace" class="headerlink" title="public class Demo01OutputStream {    public static void main(String[] args) {        try {            FileOutputStream fos &#x3D; new FileOutputStream(“F:\a.txt”);            fos.write(97);            fos.close();        } catch (IOException e) {            e.printStackTrace();        }    }}"></a>public class Demo01OutputStream {<br>    public static void main(String[] args) {<br>        try {<br>            FileOutputStream fos &#x3D; new FileOutputStream(“F:\a.txt”);<br>            fos.write(97);<br>            fos.close();<br>        } catch (IOException e) {<br>            e.printStackTrace();<br>        }<br>    }<br>}</h2><p>public class Demo01OutputStream {<br>    public static void main(String[] args) throws IOException {</p>
<pre><code>    FileOutputStream fos = new FileOutputStream(&quot;F:\\a.txt&quot;);
    fos.write(97);//a
    fos.close();

    FileOutputStream f = new FileOutputStream(new File(&quot;F:\\b.txt&quot;));
    f.write(49);
    f.write(48);
    f.write(48);//100
    f.close();
    /*
        public void write(byte[] b)
        一次写入多个字节
        如果写入第一个字节是正数（0-127），那么显示时会查询ASCII表
        如果第一个字节是负数，那么第一个字节会和第二个组成中文显示，查询系统默认码表
        void write(byte[] b, int off, int len)
        写入数组指定索引内容

        写入字符串方法,使用String中的方法把字符串转换成字节数组
     */
    FileOutputStream f1 = new FileOutputStream(new File(&quot;F:\\c.txt&quot;));
    byte[] bytes1 = &#123;65,66,67,68,69&#125;;//ABCDE
    byte[] bytes2 = &#123;-65,-66,-67,68,69&#125;;//烤紻E
    f1.write(bytes1);
    f1.write(bytes2);
    f1.write(bytes2,1,3);//窘D
    byte[] bytes3 = &quot;你好&quot;.getBytes();
    f1.write(bytes3);//你好
    f1.close();
    /*
    追加写/续写
        FileOutputStream(String name,boolean append)创建一个向具有指定name的文件中写入数据的输出文件流
        FileOutputStream(File file,boolean append)创建一个向具有指定File对象表示的文件中写入数据的输出文件流
        boolean append:追加写开关
        true:创建对象不会覆盖原文件,继续在文件末尾写
        false:创建一个新文件覆盖
    写换行:
    windows:\r\n
    linux: /n
    mac:\r

     */
    FileOutputStream f2 = new FileOutputStream(new File(&quot;F:\\d.txt&quot;),true);
    for (int i = 0; i &lt; 10; i++) &#123;
        f2.write(&quot;你好&quot;.getBytes());
        f2.write(&quot;\r\n&quot;.getBytes());
    &#125;
&#125;
</code></pre>
<p>}</p>
<h2 id="字节输入流"><a href="#字节输入流" class="headerlink" title="字节输入流"></a>字节输入流</h2><p>InputStream<br>int read()<br>从该输入流读取一个字节的数据。<br>int read(byte[] b)<br>从该输入流读取最多 b.length个字节的数据为字节数组。<br>void close()<br>关闭此文件输入流并释放与流相关联的任何系统资源</p>
<p>java。io.FileInputStream extends InputStream<br>文件字节输入流<br>把硬盘文件中的数据读入到内存中使用<br>构造方法：<br>FileInputStream(String name)<br>通过打开与实际文件的连接来创建一个 FileInputStream ，该文件由文件系统中的路径名 name命名。<br>FileInputStream(File file)<br>通过打开与实际文件的连接创建一个 FileInputStream ，该文件由文件系统中的 File对象 file命名。</p>
<p>读取数据原理（内存-&gt;硬盘)<br>    java程序-&gt;JVM-&gt;OS(操作系统)-&gt;OS调用读取数据方法-&gt;读取文件</p>
<p>public class Demo01InputStream {<br>    public static void main(String[] args) throws IOException {<br>        &#x2F;&#x2F;1. 创建对象<br>        FileInputStream fis &#x3D; new FileInputStream(“F:\a.txt”);&#x2F;&#x2F;abcd<br>        &#x2F;&#x2F;2. read方法读取<br>        int len &#x3D; fis.read();&#x2F;&#x2F;97<br>        System.out.println(len);<br>        len &#x3D; fis.read();&#x2F;&#x2F;98<br>        System.out.println(len);<br>        len &#x3D; fis.read();&#x2F;&#x2F;99<br>        System.out.println(len);<br>        len &#x3D; fis.read();&#x2F;&#x2F;100<br>        System.out.println(len);<br>        len &#x3D; fis.read();&#x2F;&#x2F;读到末尾返回-1<br>        System.out.println(len);<br>        fis.close();</p>
<pre><code>    //一次读入多字节
    FileInputStream fis2 = new FileInputStream(&quot;F:\\a.txt&quot;);//abcd
    byte[] bytes = new byte[2];
    int len2 = fis2.read(bytes);//读取的有效字节数
    System.out.println(len2);//2
    System.out.println(Arrays.toString(bytes));//[97,98]
    System.out.println(new String(bytes));//ab

    fis2.close();
&#125;
</code></pre>
<p>}</p>
<hr>
<h2 id="练习：文件复制"><a href="#练习：文件复制" class="headerlink" title="练习：文件复制"></a>练习：文件复制</h2><p>&#x2F;*<br>    文件复制<br>    一读一写<br>    数据源:E:\图片\头像\1.jpg<br>    目的地:E:\图片\1.jpg<br>    复制步骤<br>    1. 创建一个字节输入流对象,构造方法中绑定要读取的数据源<br>    2. 创建一个字节输出流对象,构造方法中绑定要写入的目的地<br>    3. 使用字节输入流中的read读取文件<br>    4. 使用字节输出流中的方法write,把读取到的字节写入到目的地的文件中<br>    5. 释放资源<br> *&#x2F;<br>public class Demo01CopyFile {<br>    public static void main(String[] args) throws IOException {<br>        &#x2F;&#x2F;1,创建输入流<br>        FileInputStream fis &#x3D; new FileInputStream(“E:\图片\头像\1.jpg”);<br>        &#x2F;&#x2F;2. 创建输出流<br>        FileOutputStream fos &#x3D; new FileOutputStream(“E:\图片\1.jpg”);<br>        &#x2F;&#x2F;3. read<br>&#x2F;&#x2F;		&#x2F;&#x2F;一次读取一个字节,写入一个字节的方式<br>&#x2F;&#x2F;		int len &#x3D; 0;<br>&#x2F;&#x2F;		while((len &#x3D; fis.read())!&#x3D;-1){<br>&#x2F;&#x2F;			fos.write(len);<br>&#x2F;&#x2F;		}</p>
<pre><code>    //使用数组缓冲读取多个字节,写入多个字节
    byte[] bytes = new byte[1024];
    int len = 0;
    while((len = fis.read(bytes))!=-1)&#123;
        fos.write(bytes,0,len);
    &#125;
    //5. 释放资源,先关写的,再关读的
    fos.close();
    fis.close();
&#125;
</code></pre>
<p>}</p>
<h2 id="字符流"><a href="#字符流" class="headerlink" title="字符流"></a>字符流</h2><p>使用字节流读取中文的问题，编码不同使用字节流容易出现问题，使用字符流</p>
<p>字符输入流<br>java.io.Reader 字符输入流最顶层的父类<br>共性成员方法:<br>    int read() 读一个字符<br>    int read(char[] cbuf) 将字符读入数组。<br>    void close() 关闭流并释放与之相关联的任何系统资源。 </p>
<p>&#x2F;*<br>    java.io.FileReader extends InputStreamReader extends Reader<br>    FileReader:文件字符输入流<br>    作用:把硬盘文件中的数据以字符的方式读取<br>    构造方法:<br>    FileReader(String fileName)<br>    FileReader(File file)</p>
<p> <em>&#x2F;<br>public class Demo01Reader {<br>    public static void main(String[] args) throws IOException {<br>        FileReader fr &#x3D; new FileReader(“F:\a.txt”);<br>&#x2F;&#x2F;		int len &#x3D; 0;<br>&#x2F;&#x2F;		while((len &#x3D; fr.read())!&#x3D;-1){<br>&#x2F;&#x2F;			System.out.print((char) len);&#x2F;&#x2F;你好abcd<br>&#x2F;&#x2F;<br>&#x2F;&#x2F;		}<br>        &#x2F;&#x2F;一次读取多个字符<br>        char[] cs &#x3D; new char[1024];<br>        int len &#x3D; 0;<br>        while((len &#x3D; fr.read(cs))!&#x3D;-1){<br>            &#x2F;</em><br>                String构造方法<br>                把字符数组转换成字符串<br>             *&#x2F;<br>            System.out.println(new String(cs,0,len));&#x2F;&#x2F;你好abcd<br>        }<br>        fr.close();<br>    }<br>}</p>
<h2 id="字符输出流"><a href="#字符输出流" class="headerlink" title="字符输出流"></a>字符输出流</h2><p>java.io.Writer:字符输出流,是所有字符输出流的最顶层的父类,是一个抽象类<br>共性的成员方法:<br>void write(int c)  写一个字符<br>void write(char[] cbuf) 写入一个字符数组。<br>abstract void write(char[] cbuf, int off, int len) 写入字符数组的一部分。<br>void write(String str) 写一个字符串<br>void write(String str, int off, int len) 写一个字符串的一部分。<br>abstract void<br>flush() 刷新流。<br>abstract void<br>close() 关闭流，先刷新。  </p>
<p>&#x2F;*<br>java.io.FileWriter extends OutputStreamWriter extends Writer<br>FileWriter: 文件字符输出流<br>作用:把内存中的字符数据写到文件中<br>构造方法:<br>FileWriter(File file)<br>FileWriter(String fileName)</p>
<p> *&#x2F;<br>public class Demo01Writer {<br>    public static void main(String[] args) throws IOException {<br>        &#x2F;&#x2F;1. 创建FileWriter对象<br>        FileWriter fw &#x3D; new FileWriter(“F:\d.txt”);<br>        &#x2F;&#x2F;2. write方法把数据写入到内存缓冲区<br>        fw.write(97);<br>        &#x2F;&#x2F;3. flush把内存缓冲区的数据刷新到文件中<br>        fw.flush();<br>        &#x2F;&#x2F;刷新后流可以继续使用<br>        fw.write(98);</p>
<pre><code>    fw.close();

    FileWriter fw2 = new FileWriter(&quot;F:\\d.txt&quot;,true);
    char[] cs = &#123;&#39;a&#39;,&#39;b&#39;,&#39;c&#39;,&#39;d&#39;&#125;;
    fw2.write(cs);
    fw2.write(&quot;\r\n&quot;);
    fw2.write(cs,1,3);
    fw2.flush();
    fw2.close();
&#125;
</code></pre>
<p>}</p>
<hr>
<h2 id="IO异常处理"><a href="#IO异常处理" class="headerlink" title="IO异常处理"></a>IO异常处理</h2><p>public class Demo02TryCatch {<br>    public static void main(String[] args) {<br>        &#x2F;&#x2F;提高变量fw的作用域,需要初始化值<br>        FileWriter fw &#x3D; null;<br>        try {<br>            fw &#x3D; new FileWriter(“F:\d.txt”);<br>            fw.write(99);<br>            fw.write(98);<br>            fw.write(97);<br>        } catch (IOException e) {<br>            e.printStackTrace();<br>        }finally {<br>            &#x2F;&#x2F;如果创建对象失败了,fw默认是空,会出现空指针异常,加一个判断<br>            if(fw!&#x3D;null){<br>                try {<br>                    fw.flush();<br>                    fw.close();<br>                } catch (IOException e) {<br>                    e.printStackTrace();<br>                }<br>            }</p>
<pre><code>    &#125;
&#125;
</code></pre>
<h2 id=""><a href="#" class="headerlink" title="}"></a>}</h2><p>JDK7之后，在try后边增加一个(),在括号中可以定义流对象<br>那么这个流对象的作用域就在try中有效<br>try中的代码执行完毕,会自动把流对象释放,不用写finally<br>格式:<br>try(定义流对象;定义流对象…){<br>    可能出现异常的代码<br>}catch(异常类变量 变量名){<br>    异常的处理逻辑<br>}</p>
<h2 id="public-class-Demo02CopyFile-public-static-void-main-String-args-try-x2F-x2F-1-创建输入流-FileInputStream-fis-x3D-new-FileInputStream-“E-图片-头像-1-jpg”-x2F-x2F-2-创建输出流-FileOutputStream-fos-x3D-new-FileOutputStream-“E-图片-1-jpg”-byte-bytes-x3D-new-byte-1024-int-len-x3D-0-while-len-x3D-fis-read-bytes-x3D-1-fos-write-bytes-0-len-catch-IOException-e-System-out-println-e"><a href="#public-class-Demo02CopyFile-public-static-void-main-String-args-try-x2F-x2F-1-创建输入流-FileInputStream-fis-x3D-new-FileInputStream-“E-图片-头像-1-jpg”-x2F-x2F-2-创建输出流-FileOutputStream-fos-x3D-new-FileOutputStream-“E-图片-1-jpg”-byte-bytes-x3D-new-byte-1024-int-len-x3D-0-while-len-x3D-fis-read-bytes-x3D-1-fos-write-bytes-0-len-catch-IOException-e-System-out-println-e" class="headerlink" title="public class Demo02CopyFile {    public static void main(String[] args) {        try(&#x2F;&#x2F;1,创建输入流            FileInputStream fis &#x3D; new FileInputStream(“E:\图片\头像\1.jpg”);            &#x2F;&#x2F;2. 创建输出流            FileOutputStream fos &#x3D; new FileOutputStream(“E:\图片\1.jpg”)){            byte[] bytes &#x3D; new byte[1024];            int len &#x3D; 0;            while((len &#x3D; fis.read(bytes))!&#x3D;-1){                fos.write(bytes,0,len);            }        }catch(IOException e){            System.out.println(e);        }    }}"></a>public class Demo02CopyFile {<br>    public static void main(String[] args) {<br>        try(&#x2F;&#x2F;1,创建输入流<br>            FileInputStream fis &#x3D; new FileInputStream(“E:\图片\头像\1.jpg”);<br>            &#x2F;&#x2F;2. 创建输出流<br>            FileOutputStream fos &#x3D; new FileOutputStream(“E:\图片\1.jpg”)){<br>            byte[] bytes &#x3D; new byte[1024];<br>            int len &#x3D; 0;<br>            while((len &#x3D; fis.read(bytes))!&#x3D;-1){<br>                fos.write(bytes,0,len);<br>            }<br>        }catch(IOException e){<br>            System.out.println(e);<br>        }<br>    }<br>}</h2><p>JDK9新特性<br>try前面可以定义流对象<br>在try后面的()中可以直接引入流对象的名称(变量名)<br>在try代码执行完毕后,流对象也可以释放掉,不要写finally<br>格式:<br>    A a &#x3D; new A();<br>    B b &#x3D; new B();<br>    try(a,b){<br>    }catch(){<br>    }</p>
<h2 id="属性集"><a href="#属性集" class="headerlink" title="属性集"></a>属性集</h2><p>Properties 类表示一个持久的属性集。<br>Properties可保存在流中或从流中加载。属性列表中每个键及其对应值都是一个字符串<br>&#x2F;*<br>    java.util.Properties集合 extends Hashtable&lt;k,v&gt; implements Map&lt;k,v&gt;<br>    Properties集合是唯一一个和IO流相结合的集合<br>     可以使用Properties集合中的方法store,把集合中的临时数据,持久化写入到硬盘存储<br>     load,把硬盘中保存的文件(键值对),读取到集合中使用</p>
<p> *&#x2F;<br>public class Demo01Properties {<br>    public static void main(String[] args) throws IOException {<br>        show01();<br>        System.out.println(“————————————“);<br>        show02();<br>        System.out.println(“————————————“);<br>        show03();<br>    }</p>
<pre><code>/*
    使用Properties集合存储数据,遍历取出Properties集合中的数据
    Properties集合是一个双列集合,key和value默认都是字符串
    Properties集合有一些操作字符串的特有方法
        Object setProperty(String key,String value) 调用Hashtable 的方法put
        String getProperty(String key) 通过key找到value值,此方法相当于Map集合中的get(key)方法
        Set&lt;String&gt; stringPropertyNames() 返回此属性列表
 */

private static void show01() &#123;
    //创建Properties集合对象
    Properties prop = new Properties();
    //使用setProperty往集合中添加数据
    prop.setProperty(&quot;田世庆&quot;,&quot;172&quot;);
    prop.setProperty(&quot;呈呈&quot;,&quot;160&quot;);
    prop.setProperty(&quot;西门吹雪&quot;,&quot;180&quot;);
    //prop.put(1,true);

    //使用stringPropertyNames把Properties集合的到一个Set集合中
    Set&lt;String&gt; set = prop.stringPropertyNames();

    //遍历set集合,取出每一个键
    for(String key:set)&#123;
        //使用getProperty方法通过key获取value
        String value = prop.getProperty(key);
        System.out.println(key+&quot;=&quot;+value);
    &#125;

&#125;
/*
    void store(OutputStream out,String comments)
    void store(Writer writer,String comments)
    参数:
        OutputStream out: 字节输出流,不能写入中文
        Writer writer: 字符输出流,可以写中文
        String comments: 注释,用来解释说明保存的文件是做什么的,不能使用中文,默认是unicode编码
    使用步骤:
        1. 创建Properties集合对象,添加数据
        2. 创建字节输出流/字符输出流对象,构造方法中绑定要输出的目的地
        3. 使用Properties集合中的方法store,把集合中的临时数据,持久化写入到硬盘中存储
        4. 释放资源

 */
private static void show02() throws IOException &#123;
    //创建Properties集合对象
    Properties prop = new Properties();
    //使用setProperty往集合中添加数据
    prop.setProperty(&quot;田世庆&quot;,&quot;172&quot;);
    prop.setProperty(&quot;呈呈&quot;,&quot;160&quot;);
    prop.setProperty(&quot;西门吹雪&quot;,&quot;180&quot;);

    //创建字符流输出对象
    FileWriter fw = new FileWriter(&quot;F:\\d.txt&quot;);
    prop.store(fw,&quot;save data&quot;);
    fw.close();
&#125;

/*
    使用load方法,把硬盘中保存的文件(键值对),读取到集合中使用
    void load(InputStream inStream)
    void load(Reader reader)
    参数:
        InputStream inStream: 字节输入流,不能读取含有中文的键值对
        Reader reader: 字符输入流,能读取含有中文的键值对
    使用步骤:
        1. 创建Properties集合对象
        2. 使用Properties集合对象中的方法load读取保存键值对的文件
        3. 遍历Properties集合
    注意:
        1. 存储键值对的文件中,键与值默认的连接符号可以使用=,空格(其他符号)
        2. 存储键值对的文件中,可以使用#进行注释,被注释的键值对不会再被读取
        3. 存储键值对的文件中,键与值默认都是字符串,不用再加引号

 */

private static void show03() throws IOException &#123;
    Properties prop = new Properties();
    prop.load(new FileReader(&quot;F:\\d.txt&quot;));
    Set&lt;String&gt; set = prop.stringPropertyNames();
    for (String key : set) &#123;
        String value = prop.getProperty(key);
        System.out.println(key+&quot;=&quot;+value);
    &#125;
&#125;
</code></pre>
<h2 id="-1"><a href="#-1" class="headerlink" title="}"></a>}</h2><h2 id="缓冲流"><a href="#缓冲流" class="headerlink" title="缓冲流"></a>缓冲流</h2><p>字节缓冲输入流，给基本的字节输入流增加一个缓冲区(数组)提高基本的字节输入流的读取效率<br>BufferedInputStream(new FileInputStream)</p>
<p>缓冲流的基本原理,是在创建流对象的同时,创建一个内置的默认大小的缓冲区数组,通过缓冲区读写,<br>减少系统IO次数,从而提高读写的效率</p>
<p>字节缓冲流: BufferedInputStream,BufferedOutputStream<br>字符缓冲流: BufferedReader, BufferedWriter</p>
<p>&#x2F;*<br>    java.io.BufferedOutputStream extends OutputStream<br>    BufferedOutputStream: 字节缓冲输出流</p>
<pre><code>构造方法:
    BufferedOutputStream(OutputStream out) 创建一个新的缓冲流,以将数据写入指定的底层输出流
    BufferedOutputStream(OutputStream out, int size) 创建一个新的缓冲输出流,以将指定缓冲区大小数据写入指定的底层输出流

使用步骤:
    1. 创建FileOutputStream对象,构造方法中绑定要输出的目的地
    2. 创建BufferedOutputStream对象,构造方法中传递FileOutputStream对象
    3. write
    4. flush
    5. close
</code></pre>
<p> *&#x2F;<br>public class Demo01BufferedOutputStream {<br>    public static void main(String[] args) throws IOException {<br>        FileOutputStream fos &#x3D; new FileOutputStream(“F:\d.txt”);<br>        BufferedOutputStream bos &#x3D; new BufferedOutputStream(fos);<br>        bos.write(“我把数据写入到内部缓冲区中”.getBytes());<br>        bos.flush();<br>        bos.close();</p>
<pre><code>    /*
        java.io.BufferedInputStream extends InputStream
        BufferedInputStream: 字节缓冲输出流

        构造方法:
            BufferedInputStream(InputStream in) 创建一个新的缓冲流,以将数据写入指定的底层输入流
            BufferedInputStream(InputStream in, int size) 创建一个新的缓冲输出流,以将指定缓冲区大小数据写入指定的底层输入流
     */

    FileInputStream fis = new FileInputStream(&quot;F:\\d.txt&quot;);
    BufferedInputStream bis = new BufferedInputStream(fis);
    int len = 0;
    while((len = bis.read())!=-1)&#123;
        System.out.println(len);
    &#125;
    bis.close();
&#125;
</code></pre>
<p>}</p>
<p>使用缓冲流效率更高</p>
<h2 id="字符缓冲流"><a href="#字符缓冲流" class="headerlink" title="字符缓冲流"></a>字符缓冲流</h2><p>public class Demo03BufferedWriter {<br>    &#x2F;*<br>        java.io.BufferedWriter extends Writer<br>        特有的成员方法:<br>            void newLine() 写入一个行分隔符,会根据不同的操作系统,获取不同的行分隔符<br>     *&#x2F;<br>    public static void main(String[] args) throws IOException {<br>        BufferedWriter bw &#x3D; new BufferedWriter(new FileWriter(“F:\d.txt”));<br>        for (int i &#x3D; 0; i &lt; 10; i++) {<br>            bw.write(“田世庆”);<br>            &#x2F;&#x2F;bw.write(“\r\n”);<br>            bw.newLine();&#x2F;&#x2F;自动换行<br>        }<br>        bw.flush();<br>        bw.close();</p>
<pre><code>    /*
        字符缓冲输入流
        特有的方法:
            String readLine() 读取一行数据

     */
    BufferedReader br = new BufferedReader(new FileReader(&quot;F:\\d.txt&quot;));
    String line1 = br.readLine();
    System.out.println(line1);
    br.close();
&#125;
</code></pre>
<p>}</p>
<h2 id="练习"><a href="#练习" class="headerlink" title="练习:"></a>练习:</h2><p>对文本内容进行排序<br>(3.入其城，则四顾萧条，寒水自碧，暮色渐起，戍角悲吟。<br>2.夜雪初霁，荠麦弥望。<br>8.自胡马窥江去后，废池乔木，犹厌言兵。<br>4.予怀怆然，感慨今昔，因自度此曲。<br>5.千岩老人以为有“黍离”之悲也。<br>7.过春风十里，尽荠麦青青。<br>11.纵豆蔻词工，青楼梦好，难赋深情。<br>9.渐黄昏，清角吹寒，都在空城。<br>10.杜郎俊赏，算而今、重到须惊。<br>12.二十四桥仍在，波心荡、冷月无声。<br>1.淳熙丙申至日，予过维扬。<br>13.念桥边红药，年年知为谁生。<br>6.淮左名都，竹西佳处，解鞍少驻初程。)</p>
<p>&#x2F;*<br>    分析:<br>        1. 创建一个HashMap对象,可以存储每行文本的序号(1,2,3,…);value:存储每行文本<br>        2. 创建字符缓冲输入流对象,构造方法中绑定字符输入流<br>        3. 创建字符缓冲输出流对象<br>        4. 使用字符缓冲输入流中的方法readline,逐行读取文本<br>        5. 对读取到的文本切割,获取行中的序号和文本内容<br>        6. 把切割好的序号和文本的内容存储到HashMap集合中(key序号是有序的,会自动排序1,2,3…)<br>        7. 遍历HashMap,获取每一个键值对<br>        8. 把每一个键值对,拼接为一个文本行<br>        9. 把拼接好的文本,使用字符缓冲输出流中的方法write写入文件中<br>        10.释放资源</p>
<p> <em>&#x2F;<br>&#x2F;</em><br>    分析:<br>        1. 创建一个HashMap对象,可以存储每行文本的序号(1,2,3,…);value:存储每行文本<br>        2. 创建字符缓冲输入流对象,构造方法中绑定字符输入流<br>        3. 创建字符缓冲输出流对象<br>        4. 使用字符缓冲输入流中的方法readline,逐行读取文本<br>        5. 对读取到的文本切割,获取行中的序号和文本内容<br>        6. 把切割好的序号和文本的内容存储到HashMap集合中(key序号是有序的,会自动排序1,2,3…)<br>        7. 遍历HashMap,获取每一个键值对<br>        8. 把每一个键值对,拼接为一个文本行<br>        9. 把拼接好的文本,使用字符缓冲输出流中的方法write写入文件中<br>        10.释放资源</p>
<p> *&#x2F;<br>public class Demo01SortTxt {<br>    public static void main(String[] args) throws IOException {<br>        HashMap&lt;String,String&gt; map &#x3D; new HashMap&lt;&gt;();<br>        BufferedReader br &#x3D; new BufferedReader(new FileReader(“F:\扬州慢.txt”));&#x2F;&#x2F;要用utf8编码存储<br>        BufferedWriter bw &#x3D; new BufferedWriter(new FileWriter(“F:\扬州慢2.txt”));<br>        String line;<br>        while ((line &#x3D; br.readLine())!&#x3D;null){<br>            String[] arr &#x3D; line.split(“\.”);<br>            map.put(arr[0],arr[1]);<br>        }</p>
<pre><code>    for (String key : map.keySet()) &#123;
        String s = key+ &quot;.&quot; + map.get(key);
</code></pre>
<p>&#x2F;&#x2F;			System.out.println(s);<br>            bw.write(s);<br>            bw.newLine();<br>        }<br>        bw.flush();<br>        bw.close();<br>        br.close();<br>    }<br>}</p>
<h2 id="转换流"><a href="#转换流" class="headerlink" title="转换流"></a>转换流</h2><p>FileReader可以读取IDE默认编码格式（UTF-8）的文件<br>FileReader读取系统默认编码（中文GBK）会产生乱码<br>要读取默认编码，需要转换流<br>InputStreamReader 字节流通向字符流的桥梁<br>OutputStreamWriter 字符流通向字节流的桥梁</p>
<p>&#x2F;*<br>    java.io.OutputStreamWriter extends Writer<br>    OutputStreamWriter: 可使用指定的字符集将写入流中的字符编码成字节<br>    构造方法:<br>    OutputStreamWriter(OutputStream out)创建使用默认字符编码的OutputStreamWriter<br>    OutputStreamWriter(OutputStream out,String charsetName)创建使用指定字符编码的OutputStreamWriter,不指定默认使用utf-8<br>    使用步骤:<br>    1. 创建OutputStreamWriter对象,构造方法中传递字节输出流和指定的编码表名称<br>    2. 使用OutputStreamWriter对象中的方法writer,吧字符转换为字节存储缓冲区中(编码)<br>    3. 使用OutputStreamWriter对象中的方法flush<br>    4.close</p>
<p> *&#x2F;<br>public class Demo01OutputStreamWriter {<br>    public static void main(String[] args) throws IOException {<br>        write_utf_8();<br>        write_gbk();</p>
<pre><code>    read_utf_8();
    System.out.println(&quot;--------------------------&quot;);
    read_gbk();
&#125;


private static void write_gbk() throws IOException &#123;
    OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream(&quot;F:\\gbk.txt&quot;),&quot;gbk&quot;);
    osw.write(&quot;你好&quot;);
    osw.flush();
    osw.close();

&#125;

private static void write_utf_8() throws IOException &#123;
    OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream(&quot;F:\\utf-8.txt&quot;),&quot;utf-8&quot;);
    osw.write(&quot;你好&quot;);
    osw.flush();
    osw.close();
&#125;


/*
    java.io.InputStreamReader extends Reader
    构造方法:
    InputStreamReader(InputStream in)
    InputStreamReader(InputStream in,String charsetName)

    注意事项:
    构造方法中指定的编码表名称要和文件的编码相同,否则会乱码
 */

private static void read_utf_8() throws IOException &#123;
    InputStreamReader isr = new InputStreamReader(new FileInputStream(&quot;F:\\utf-8.txt&quot;));//不指定默认使用u8
    int len = 0;
    while((len = isr.read())!=-1)&#123;
        System.out.println((char)len);
    &#125;
    isr.close();
&#125;

private static void read_gbk() throws IOException &#123;
    InputStreamReader isr = new InputStreamReader(new FileInputStream(&quot;F:\\gbk.txt&quot;),&quot;gbk&quot;);
    int len = 0;
    while((len = isr.read())!=-1)&#123;
        System.out.println((char)len);
    &#125;
    isr.close();
&#125;
</code></pre>
<p>}</p>
<h2 id="练习-1"><a href="#练习-1" class="headerlink" title="练习"></a>练习</h2><p>转换文件编码</p>
<p>&#x2F;*<br>    练习:转换编码<br>    将GBK编码的文件转换为UTF-8的文本文件<br>    分析:<br>        1. 创建InputStreamReader对象,构造方法中传递字节输入流和指定的编码表名称GBK<br>        2. 创建OutputStreamWriter对象,构造方法中传递字节输出流和指定的编码表名称UTF-8<br>        3. 使用InputStreamReader对象中的方法read读取文件<br>        4. 使用OutputStreamWriter对象中的方法write,把读取的数据写入到文件中<br>        5. 释放</p>
<p> *&#x2F;</p>
<p>public class ChangeCode {<br>    public static void main(String[] args) throws IOException {<br>        InputStreamReader isr &#x3D; new InputStreamReader(new FileInputStream(“F:\gbk.txt”),”gbk”);<br>        OutputStreamWriter osw &#x3D; new OutputStreamWriter(new FileOutputStream(“F:\gbk2u8.txt”),”utf-8”);<br>        int len &#x3D; 0;<br>        while((len &#x3D; isr.read())!&#x3D;-1){<br>            osw.write(len);<br>        }<br>        osw.flush();<br>        osw.close();<br>        isr.close();<br>    }<br>}</p>
<h2 id="序列化和反序列化"><a href="#序列化和反序列化" class="headerlink" title="序列化和反序列化"></a>序列化和反序列化</h2><p>Person p &#x3D; new Person(“TT”,18);<br>把对象以流的方式,写入到文件中保存,叫写对象,也叫对象的序列化<br>对象中包含的不仅仅是字符,使用字节流<br>ObjectOutputStream:对象的序列化流</p>
<p>把文件中保存的对象,以流的方式读取出来,叫做读对象,也叫对象的反序列化<br>读取的文件保存的都是字节,使用字节流<br>ObjectInputStream:对象的反序列化流</p>
<p>&#x2F;*<br>    java.io.ObjectOutputStream extends OutputStream<br>    ObjectOutputStream:对象的序列化流<br>    作用:把对象以流的方式写入到文件中保存<br>    构造方法:<br>    ObjectOutputStream(OutputStream out) 创建写入指定 OutputStream 的ObjectOutputStream<br>    特有的成员方法:<br>    void writeObject(Object obj) 将指定的对象写入ObjectOutputStream<br>    使用步骤:<br>    1. 创建ObjectOutputStream,构造方法中传递字节输出流<br>    2. 使用writeObject方法,把对象写入到文件中<br>    3. 释放资源</p>
<pre><code>类通过实现Serializable接口以启用序列化功能
</code></pre>
<p> *&#x2F;<br>public class Demo01ObjectOutputStream {<br>    public static void main(String[] args) throws IOException, ClassNotFoundException {<br>        ObjectOutputStream oos &#x3D; new ObjectOutputStream(new FileOutputStream(“F:\person.txt”));<br>        oos.writeObject(new Person(“TT”,16));<br>        oos.close();</p>
<pre><code>    /*
        java.io.ObjectInputStream extends InputStream
        把文件中保存的对象以流的方式读取出来
        构造方法:
        ObjectInputStream(InputStream in) 创建指定InputStream读取的ObjectInputStream

        特有的成员方法:
        Object readObject() 从ObjectInputStream读取对象

        使用步骤:
            1. 创建ObjectInputStream,构造方法中传递字节输入流
            2. 使用readObject方法,把对象写入到文件中
            3. 释源
            4.使用读取出来的对象

        readObject方法声明抛出了ClassNotFoundException(class文件找不到异常);
        当不存在对象的class文件时抛出异常
        反序列化的前提:
        1. 类必须实现Serializable
        2. 必须存在类对应class文件
     */
    ObjectInputStream ois = new ObjectInputStream(new FileInputStream(&quot;F:\\person.txt&quot;));
    Object o = ois.readObject();
    ois.close();
    System.out.println(o);
&#125;
</code></pre>
<p>}</p>
<h2 id="transient关键字：瞬态关键字"><a href="#transient关键字：瞬态关键字" class="headerlink" title="transient关键字：瞬态关键字"></a>transient关键字：瞬态关键字</h2><p>static：静态关键字，优先于非静态加载到内存中（静态优先于对象进入内存），被static修饰的成员不能被序列化，序列化的都是对象<br>transient：修饰后，不能被序列化。如果只是不想某变量被序列化，就用transient</p>
<p>Person类修改后，序列号会发生改变，反序列化会失败<br>问题：每次修改类的定义，都会给class文件生成一个新的序列号<br>解决方案：无论是否对类的定义进行修改，都不重新生生成序列号，可以手动给类添加一个序列号<br>private static final long serialVersionUID &#x3D; 1L;</p>
<h2 id="练习-2"><a href="#练习-2" class="headerlink" title="练习"></a>练习</h2><p>&#x2F;*<br>    练习:序列化集合<br>    当我们想在文件中保存多个对象的时候<br>    可以把多个对象存储到一个集合中<br>    对集合进行序列化和反序列化<br>    分析:<br>    1. 定义一个存储Person对象的ArrayList集合<br>    2. 往ArrayList集合中存储Person对象<br>    3. 创建一个序列化流ObjectOutputStream对象<br>    4. 使用writeObject对集合序列化<br>    5. 创建一个反序列化对象<br>    6. 使用readObject读取文件中保存的集合<br>    7. 把Object类型的集合转换成ArrayList类型<br>    8. 遍历ArrayList集合<br>    9. 释放资源</p>
<p> *&#x2F;<br>public class SerializationExercise {<br>    public static void main(String[] args) throws IOException, ClassNotFoundException {<br>        ArrayList<Person> list &#x3D; new ArrayList&lt;&gt;();<br>        list.add(new Person(“TT”,16));<br>        list.add(new Person(“CC”,18));<br>        list.add(new Person(“YY”,15));<br>        ObjectOutputStream oos &#x3D; new ObjectOutputStream(new FileOutputStream(“F:\list.txt”));<br>        oos.writeObject(list);<br>        ObjectInputStream ois &#x3D; new ObjectInputStream(new FileInputStream(“F:\list.txt”));<br>        Object o &#x3D;ois.readObject();<br>        ArrayList<Person> list2 &#x3D; (ArrayList<Person>)o;</p>
<pre><code>    for (Person person : list2) &#123;
        System.out.println(person);
    &#125;
    ois.close();
    oos.close();
&#125;
</code></pre>
<p>}</p>
<h2 id="打印流"><a href="#打印流" class="headerlink" title="打印流"></a>打印流</h2><p>java.io.PrintStream:打印流,为其他输出流添加了功能,使他能够方便地打印各种数据值表示形式<br>PrintStream特点:</p>
<ol>
<li>只负责数据的输出,不负责数据的读取</li>
<li>与其他输出流不同,PrintStream 永远不会抛出 IOException</li>
<li>有特有的方法,print,println</li>
</ol>
<p>注意:如果使用继承父类的write方法写数据,那么查看数据的时候会查询编码表,使用自己的就原样输出</p>
<p>PrintStream ps &#x3D; new PrintStream(“F:\d.txt”);<br>ps.write(97); &#x2F;&#x2F;&#x3D;&gt; a<br>ps.println(91) &#x2F;&#x2F;&#x3D;&gt; 97<br>ps.close();</p>
<p>可以改变输出语句的目的地<br>输出语句默认在控制台输出,使用System.setOut方法改变输出语句的目的地为参数中传递的打印流目的地</p>
<p>sout(“控制台输出”);</p>
<p>PrintStream ps &#x3D; new PrintStream(“F:\d.txt”);<br>System.setOut(ps);&#x2F;&#x2F;把输出语句目的地改为d.txt<br>sout(“目的地输出”);&#x2F;&#x2F;会打印在d.txt中</p>

                
            </div>
            <hr/>

            

    <div class="reprint" id="reprint-statement">
        
            <div class="reprint__author">
                <span class="reprint-meta" style="font-weight: bold;">
                    <i class="fas fa-user">
                        文章作者:
                    </i>
                </span>
                <span class="reprint-info">
                    <a href="/shiqing/about" rel="external nofollow noreferrer">ShiQing</a>
                </span>
            </div>
            <div class="reprint__type">
                <span class="reprint-meta" style="font-weight: bold;">
                    <i class="fas fa-link">
                        文章链接:
                    </i>
                </span>
                <span class="reprint-info">
                    <a href="https://shiqing.gitee.io/shiqing/2020/03/26/java-ji-chu/javanote06-iostream/">https://shiqing.gitee.io/shiqing/2020/03/26/java-ji-chu/javanote06-iostream/</a>
                </span>
            </div>
            <div class="reprint__notice">
                <span class="reprint-meta" style="font-weight: bold;">
                    <i class="fas fa-copyright">
                        版权声明:
                    </i>
                </span>
                <span class="reprint-info">
                    本博客所有文章除特別声明外，均采用
                    <a href="https://creativecommons.org/licenses/by/4.0/deed.zh" rel="external nofollow noreferrer" target="_blank">CC BY 4.0</a>
                    许可协议。转载请注明来源
                    <a href="/shiqing/about" target="_blank">ShiQing</a>
                    !
                </span>
            </div>
        
    </div>

    <script async defer>
      document.addEventListener("copy", function (e) {
        let toastHTML = '<span>复制成功，请遵循本文的转载规则</span><button class="btn-flat toast-action" onclick="navToReprintStatement()" style="font-size: smaller">查看</a>';
        M.toast({html: toastHTML})
      });

      function navToReprintStatement() {
        $("html, body").animate({scrollTop: $("#reprint-statement").offset().top - 80}, 800);
      }
    </script>



            <div class="tag_share" style="display: block;">
                <div class="post-meta__tag-list" style="display: inline-block;">
                    
                        <div class="article-tag">
                            
                                <a href="/shiqing/tags/Java%E5%9F%BA%E7%A1%80/">
                                    <span class="chip bg-color">Java基础</span>
                                </a>
                            
                        </div>
                    
                </div>
                <div class="post_share" style="zoom: 80%; width: fit-content; display: inline-block; float: right; margin: -0.15rem 0;">
                    <link rel="stylesheet" type="text/css" href="/shiqing/libs/share/css/share.min.css">
<div id="article-share">

    
    <div class="social-share" data-sites="twitter,facebook,google,qq,qzone,wechat,weibo,douban,linkedin" data-wechat-qrcode-helper="<p>微信扫一扫即可分享！</p>"></div>
    <script src="/shiqing/libs/share/js/social-share.min.js"></script>
    

    

</div>

                </div>
            </div>
            
                <style>
    #reward {
        margin: 40px 0;
        text-align: center;
    }

    #reward .reward-link {
        font-size: 1.4rem;
        line-height: 38px;
    }

    #reward .btn-floating:hover {
        box-shadow: 0 6px 12px rgba(0, 0, 0, 0.2), 0 5px 15px rgba(0, 0, 0, 0.2);
    }

    #rewardModal {
        width: 320px;
        height: 350px;
    }

    #rewardModal .reward-title {
        margin: 15px auto;
        padding-bottom: 5px;
    }

    #rewardModal .modal-content {
        padding: 10px;
    }

    #rewardModal .close {
        position: absolute;
        right: 15px;
        top: 15px;
        color: rgba(0, 0, 0, 0.5);
        font-size: 1.3rem;
        line-height: 20px;
        cursor: pointer;
    }

    #rewardModal .close:hover {
        color: #ef5350;
        transform: scale(1.3);
        -moz-transform:scale(1.3);
        -webkit-transform:scale(1.3);
        -o-transform:scale(1.3);
    }

    #rewardModal .reward-tabs {
        margin: 0 auto;
        width: 210px;
    }

    .reward-tabs .tabs {
        height: 38px;
        margin: 10px auto;
        padding-left: 0;
    }

    .reward-content ul {
        padding-left: 0 !important;
    }

    .reward-tabs .tabs .tab {
        height: 38px;
        line-height: 38px;
    }

    .reward-tabs .tab a {
        color: #fff;
        background-color: #ccc;
    }

    .reward-tabs .tab a:hover {
        background-color: #ccc;
        color: #fff;
    }

    .reward-tabs .wechat-tab .active {
        color: #fff !important;
        background-color: #22AB38 !important;
    }

    .reward-tabs .alipay-tab .active {
        color: #fff !important;
        background-color: #019FE8 !important;
    }

    .reward-tabs .reward-img {
        width: 210px;
        height: 210px;
    }
</style>

<div id="reward">
    <a href="#rewardModal" class="reward-link modal-trigger btn-floating btn-medium waves-effect waves-light red">赏</a>

    <!-- Modal Structure -->
    <div id="rewardModal" class="modal">
        <div class="modal-content">
            <a class="close modal-close"><i class="fas fa-times"></i></a>
            <h4 class="reward-title">你的赏识是我前进的动力</h4>
            <div class="reward-content">
                <div class="reward-tabs">
                    <ul class="tabs row">
                        <li class="tab col s6 alipay-tab waves-effect waves-light"><a href="#alipay">支付宝</a></li>
                        <li class="tab col s6 wechat-tab waves-effect waves-light"><a href="#wechat">微 信</a></li>
                    </ul>
                    <div id="alipay">
                        <img src="/shiqing/medias/reward/alipay.jpg" class="reward-img" alt="支付宝打赏二维码">
                    </div>
                    <div id="wechat">
                        <img src="/shiqing/medias/reward/wechat.png" class="reward-img" alt="微信打赏二维码">
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
    $(function () {
        $('.tabs').tabs();
    });
</script>

            
        </div>
    </div>

    

    

    

    

    

    

    

    

<article id="prenext-posts" class="prev-next articles">
    <div class="row article-row">
        
        <div class="article col s12 m6" data-aos="fade-up">
            <div class="article-badge left-badge text-color">
                <i class="fas fa-chevron-left"></i>&nbsp;上一篇</div>
            <div class="card">
                <a href="/shiqing/2020/03/30/java-ji-chu/javanote07-tcpip/">
                    <div class="card-image">
                        
                        
                        <img src="/shiqing/medias/featureimages/4.jpg" class="responsive-img" alt="&#39;JavaNote07_TCPIP&#39;">
                        
                        <span class="card-title">&#39;JavaNote07_TCPIP&#39;</span>
                    </div>
                </a>
                <div class="card-content article-content">
                    <div class="summary block-with-text">
                        
                            网络编程1.1 软件结构C&#x2F;S结构：全称Client&#x2F;Server结构，客户端和服务器结构。QQ迅雷等B&#x2F;S结构：全称Browser&#x2F;Server结构，浏览器和服务器结构。谷歌火狐1.2 网络通信协议
                        
                    </div>
                    <div class="publish-info">
                        <span class="publish-date">
                            <i class="far fa-clock fa-fw icon-date"></i>2020-03-30
                        </span>
                        <span class="publish-author">
                            
                            <i class="fas fa-bookmark fa-fw icon-category"></i>
                            
                            <a href="/shiqing/categories/Java/" class="post-category">
                                    Java
                                </a>
                            
                            
                        </span>
                    </div>
                </div>
                
                <div class="card-action article-tags">
                    
                    <a href="/shiqing/tags/Java%E5%9F%BA%E7%A1%80/">
                        <span class="chip bg-color">Java基础</span>
                    </a>
                    
                </div>
                
            </div>
        </div>
        
        
        <div class="article col s12 m6" data-aos="fade-up">
            <div class="article-badge right-badge text-color">
                下一篇&nbsp;<i class="fas fa-chevron-right"></i>
            </div>
            <div class="card">
                <a href="/shiqing/2020/03/19/java-ji-chu/javanote05-lambda/">
                    <div class="card-image">
                        
                        
                        <img src="/shiqing/medias/featureimages/15.jpg" class="responsive-img" alt="&#39;JavaNote05_Lambda&#39;">
                        
                        <span class="card-title">&#39;JavaNote05_Lambda&#39;</span>
                    </div>
                </a>
                <div class="card-content article-content">
                    <div class="summary block-with-text">
                        
                            Lambda表达式3.1 函数式编程思想概述尽量忽略面向对象的复杂语法，强调做什么，而不是以什么形式做
面向对象的思想：做一件事情，找一个能解决这个事情的对象，调用对象的方法，完成事情函数式编程思想：只要能获取到结果，怎么做的都不重要，重视
                        
                    </div>
                    <div class="publish-info">
                            <span class="publish-date">
                                <i class="far fa-clock fa-fw icon-date"></i>2020-03-19
                            </span>
                        <span class="publish-author">
                            
                            <i class="fas fa-bookmark fa-fw icon-category"></i>
                            
                            <a href="/shiqing/categories/Java/" class="post-category">
                                    Java
                                </a>
                            
                            
                        </span>
                    </div>
                </div>
                
                <div class="card-action article-tags">
                    
                    <a href="/shiqing/tags/Java%E5%9F%BA%E7%A1%80/">
                        <span class="chip bg-color">Java基础</span>
                    </a>
                    
                </div>
                
            </div>
        </div>
        
    </div>
</article>

</div>



<!-- 代码块功能依赖 -->
<script type="text/javascript" src="/shiqing/libs/codeBlock/codeBlockFuction.js"></script>

<!-- 代码语言 -->

<script type="text/javascript" src="/shiqing/libs/codeBlock/codeLang.js"></script>


<!-- 代码块复制 -->

<script type="text/javascript" src="/shiqing/libs/codeBlock/codeCopy.js"></script>


<!-- 代码块收缩 -->

<script type="text/javascript" src="/shiqing/libs/codeBlock/codeShrink.js"></script>


    </div>
    <div id="toc-aside" class="expanded col l3 hide-on-med-and-down">
        <div class="toc-widget card" style="background-color: white;">
            <div class="toc-title"><i class="far fa-list-alt"></i>&nbsp;&nbsp;目录</div>
            <div id="toc-content"></div>
        </div>
    </div>
</div>

<!-- TOC 悬浮按钮. -->

<div id="floating-toc-btn" class="hide-on-med-and-down">
    <a class="btn-floating btn-large bg-color">
        <i class="fas fa-list-ul"></i>
    </a>
</div>


<script src="/shiqing/libs/tocbot/tocbot.min.js"></script>
<script>
    $(function () {
        tocbot.init({
            tocSelector: '#toc-content',
            contentSelector: '#articleContent',
            headingsOffset: -($(window).height() * 0.4 - 45),
            collapseDepth: Number('0'),
            headingSelector: 'h2, h3, h4'
        });

        // modify the toc link href to support Chinese.
        let i = 0;
        let tocHeading = 'toc-heading-';
        $('#toc-content a').each(function () {
            $(this).attr('href', '#' + tocHeading + (++i));
        });

        // modify the heading title id to support Chinese.
        i = 0;
        $('#articleContent').children('h2, h3, h4').each(function () {
            $(this).attr('id', tocHeading + (++i));
        });

        // Set scroll toc fixed.
        let tocHeight = parseInt($(window).height() * 0.4 - 64);
        let $tocWidget = $('.toc-widget');
        $(window).scroll(function () {
            let scroll = $(window).scrollTop();
            /* add post toc fixed. */
            if (scroll > tocHeight) {
                $tocWidget.addClass('toc-fixed');
            } else {
                $tocWidget.removeClass('toc-fixed');
            }
        });

        
        /* 修复文章卡片 div 的宽度. */
        let fixPostCardWidth = function (srcId, targetId) {
            let srcDiv = $('#' + srcId);
            if (srcDiv.length === 0) {
                return;
            }

            let w = srcDiv.width();
            if (w >= 450) {
                w = w + 21;
            } else if (w >= 350 && w < 450) {
                w = w + 18;
            } else if (w >= 300 && w < 350) {
                w = w + 16;
            } else {
                w = w + 14;
            }
            $('#' + targetId).width(w);
        };

        // 切换TOC目录展开收缩的相关操作.
        const expandedClass = 'expanded';
        let $tocAside = $('#toc-aside');
        let $mainContent = $('#main-content');
        $('#floating-toc-btn .btn-floating').click(function () {
            if ($tocAside.hasClass(expandedClass)) {
                $tocAside.removeClass(expandedClass).hide();
                $mainContent.removeClass('l9');
            } else {
                $tocAside.addClass(expandedClass).show();
                $mainContent.addClass('l9');
            }
            fixPostCardWidth('artDetail', 'prenext-posts');
        });
        
    });
</script>

    

</main>




        <footer class="page-footer bg-color">
    
    <div class="container row center-align" style="margin-bottom: 0px !important;">
        <div class="col s12 m8 l8 copy-right">
            Copyright&nbsp;&copy;
            
                <span id="year">2019-2024</span>
            
            <span id="year">2019</span>
            <a href="/shiqing/about" target="_blank">ShiQing</a>
            |&nbsp;Powered by&nbsp;<a href="https://hexo.io/" target="_blank">Hexo</a>
            |&nbsp;Theme&nbsp;<a href="https://github.com/blinkfox/hexo-theme-matery" target="_blank">Matery</a>
            <br>
            
            
            
            
            
            
            <span id="busuanzi_container_site_pv">
                |&nbsp;<i class="far fa-eye"></i>&nbsp;总访问量:&nbsp;<span id="busuanzi_value_site_pv"
                    class="white-color"></span>&nbsp;次
            </span>
            
            
            <span id="busuanzi_container_site_uv">
                |&nbsp;<i class="fas fa-users"></i>&nbsp;总访问人数:&nbsp;<span id="busuanzi_value_site_uv"
                    class="white-color"></span>&nbsp;人
            </span>
            
            <br>
            
            <br>
            
        </div>
        <div class="col s12 m4 l4 social-link social-statis">
    <a href="https://github.com/blinkfox" class="tooltipped" target="_blank" data-tooltip="访问我的GitHub" data-position="top" data-delay="50">
        <i class="fab fa-github"></i>
    </a>



    <a href="mailto:2528393970@qq.com" class="tooltipped" target="_blank" data-tooltip="邮件联系我" data-position="top" data-delay="50">
        <i class="fas fa-envelope-open"></i>
    </a>



    <a href="tencent://AddContact/?fromId=50&fromSubId=1&subcmd=all&uin=2528393970" class="tooltipped" target="_blank" data-tooltip="QQ联系我: 2528393970" data-position="top" data-delay="50">
        <i class="fab fa-qq"></i>
    </a>







    <a href="/shiqing/atom.xml" class="tooltipped" target="_blank" data-tooltip="RSS 订阅" data-position="top" data-delay="50">
        <i class="fas fa-rss"></i>
    </a>

</div>
    </div>
</footer>

<div class="progress-bar"></div>


        <!-- 搜索遮罩框 -->
<div id="searchModal" class="modal">
    <div class="modal-content">
        <div class="search-header">
            <span class="title"><i class="fas fa-search"></i>&nbsp;&nbsp;搜索</span>
            <input type="search" id="searchInput" name="s" placeholder="请输入搜索的关键字"
                   class="search-input">
        </div>
        <div id="searchResult"></div>
    </div>
</div>

<script type="text/javascript">
$(function () {
    var searchFunc = function (path, search_id, content_id) {
        'use strict';
        $.ajax({
            url: path,
            dataType: "xml",
            success: function (xmlResponse) {
                // get the contents from search data
                var datas = $("entry", xmlResponse).map(function () {
                    return {
                        title: $("title", this).text(),
                        content: $("content", this).text(),
                        url: $("url", this).text()
                    };
                }).get();
                var $input = document.getElementById(search_id);
                var $resultContent = document.getElementById(content_id);
                $input.addEventListener('input', function () {
                    var str = '<ul class=\"search-result-list\">';
                    var keywords = this.value.trim().toLowerCase().split(/[\s\-]+/);
                    $resultContent.innerHTML = "";
                    if (this.value.trim().length <= 0) {
                        return;
                    }
                    // perform local searching
                    datas.forEach(function (data) {
                        var isMatch = true;
                        var data_title = data.title.trim().toLowerCase();
                        var data_content = data.content.trim().replace(/<[^>]+>/g, "").toLowerCase();
                        var data_url = data.url;
                        data_url = data_url.indexOf('/') === 0 ? data.url : '/' + data_url;
                        var index_title = -1;
                        var index_content = -1;
                        var first_occur = -1;
                        // only match artiles with not empty titles and contents
                        if (data_title !== '' && data_content !== '') {
                            keywords.forEach(function (keyword, i) {
                                index_title = data_title.indexOf(keyword);
                                index_content = data_content.indexOf(keyword);
                                if (index_title < 0 && index_content < 0) {
                                    isMatch = false;
                                } else {
                                    if (index_content < 0) {
                                        index_content = 0;
                                    }
                                    if (i === 0) {
                                        first_occur = index_content;
                                    }
                                }
                            });
                        }
                        // show search results
                        if (isMatch) {
                            str += "<li><a href='" + data_url + "' class='search-result-title'>" + data_title + "</a>";
                            var content = data.content.trim().replace(/<[^>]+>/g, "");
                            if (first_occur >= 0) {
                                // cut out 100 characters
                                var start = first_occur - 20;
                                var end = first_occur + 80;
                                if (start < 0) {
                                    start = 0;
                                }
                                if (start === 0) {
                                    end = 100;
                                }
                                if (end > content.length) {
                                    end = content.length;
                                }
                                var match_content = content.substr(start, end);
                                // highlight all keywords
                                keywords.forEach(function (keyword) {
                                    var regS = new RegExp(keyword, "gi");
                                    match_content = match_content.replace(regS, "<em class=\"search-keyword\">" + keyword + "</em>");
                                });

                                str += "<p class=\"search-result\">" + match_content + "...</p>"
                            }
                            str += "</li>";
                        }
                    });
                    str += "</ul>";
                    $resultContent.innerHTML = str;
                });
            }
        });
    };

    searchFunc('/shiqing/search.xml', 'searchInput', 'searchResult');
});
</script>

        <!-- 回到顶部按钮 -->
<div id="backTop" class="top-scroll">
    <a class="btn-floating btn-large waves-effect waves-light" href="#!">
        <i class="fas fa-arrow-up"></i>
    </a>
</div>


        <script src="/shiqing/libs/materialize/materialize.min.js"></script>
        <script src="/shiqing/libs/masonry/masonry.pkgd.min.js"></script>
        <script src="/shiqing/libs/aos/aos.js"></script>
        <script src="/shiqing/libs/scrollprogress/scrollProgress.min.js"></script>
        <script src="/shiqing/libs/lightGallery/js/lightgallery-all.min.js"></script>
        <script src="/shiqing/js/matery.js"></script>

        <!-- Baidu Analytics -->

        <!-- Baidu Push -->

<script>
    (function () {
        var bp = document.createElement('script');
        var curProtocol = window.location.protocol.split(':')[0];
        if (curProtocol === 'https') {
            bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';
        } else {
            bp.src = 'http://push.zhanzhang.baidu.com/push.js';
        }
        var s = document.getElementsByTagName("script")[0];
        s.parentNode.insertBefore(bp, s);
    })();
</script>

        
        <script src="/shiqing/libs/others/clicklove.js" async="async"></script>
        
        
        <script async src="/shiqing/libs/others/busuanzi.pure.mini.js"></script>
        

        <script type="text/javascript">
            var OriginTitile = document.title,
                st;
            document.addEventListener("visibilitychange", function () {
                document.hidden ? (document.title = "看不见我~看不见我~", clearTimeout(st)) : (document.title =
                    "(๑•̀ㅂ•́) ✧被发现了～", st = setTimeout(function () {
                        document.title = OriginTitile
                    }, 3e3))
            })
        </script>

        <!-- 背景樱花飘落特效 -->
        
            <script type="text/javascript">
                //只在桌面版网页启用特效
                var windowWidth = $(window).width();
                if (windowWidth > 768) {
                    document.write('<script type="text/javascript" src="/js/xuehuapiaoluo.js"><\/script>');
                }
            </script>
        

        

        


        
        

        

        

        
        <script src="/shiqing/libs/instantpage/instantpage.js" type="module"></script>
        

    </body>

</html>
